import axios from 'axios'
import { ElMessage } from "element-plus";
import "element-plus/theme-chalk/el-message.css";
import { userUserStore } from '@/stores/user'
import { useRouter } from "vue-router";
const router = useRouter()

// import { Message } from 'element-ui'
const instance = axios.create({
    baseURL: 'http://192.168.10.1:6001/app/',
    timeout: 5000
  })

  import JSONBIG from 'json-bigint'

  instance.defaults.transformResponse = [
    function (data) {
      try {
        return JSONBIG.parse(data)
      } catch (err) {
        return data
      }
    }
  ]


// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    const userStore = userUserStore()
    const token = userStore.userInfo.token
    if(token){
      config.headers.AppAuthorizationToken = token
    }
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么

   const res = response.data
  //  console.log(res)
  if (res.code === 401) {
    ElMessage({ type: "error", message: res.errorMessage });
    const userStore = userUserStore()
    userStore.clearUserInfo()
    router.push('/login')
  } else if (res.code !== 200) {
    ElMessage({ type: "error", message: res.errorMessage });
    return Promise.reject(res.errorMessage)
  }
    return response.data;
  }, function (error) {
    console.log(error)
    return Promise.reject(error);
  });

export default instance